<template>
  <div class="chat-container">
    <!-- 顶部信息栏 -->
    <div class="chat-header">
      <h2>聊天室</h2>
      <div class="user-info">
        <span>当前用户：{{ username }}</span>
        <el-button type="danger" @click="disconnect" size="small">退出</el-button>
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-content">
      <!-- 右侧居民列表 -->
      <div class="user-list-container">
        <h3>居民列表</h3>
        <div class="user-item-wrapper">
          <div class="user-item" v-for="user in residents" :key="user.residentId">
            <el-avatar :src="`https://api.dicebear.com/7.x/avataaars/svg?seed=${user.residentId}`" size="small"></el-avatar>
            <span>{{ user.residentName }}</span>
            <el-button type="primary" size="mini" @click="sendToUser(user.residentName, user.residentId)">私聊</el-button>
          </div>
          <!-- 当没有居民时显示提示 -->
          <div class="empty-tip" v-if="residents.length === 0">暂无居民数据</div>
        </div>
      </div>

      <!-- 根据是否选择用户显示聊天窗口或提示信息 -->
      <div v-if="privateChatTarget" class="chat-window">
        <div class="chat-window-header">
          <el-avatar :src="`https://api.dicebear.com/7.x/avataaars/svg?seed=${selectedUserId}`" size="small"></el-avatar>
          <span>正在与 {{ privateChatTarget }} 聊天</span>
        </div>
        <!-- 聊天消息列表 -->
        <div class="message-list">
          <div v-for="message in filteredMessages" :key="getUniqueMessageKey(message)" class="message-item">
            <div v-if="message.type === 'SYSTEM'" class="system-message">
              {{ message.content }}
            </div>
            <div v-else-if="message.from === userId" class="self-message">
              <div class="message-header">
                <span class="sender">我</span>
                <span class="time">{{ formatTime(message.timestamp) }}</span>
              </div>
              <div class="message-content">
                {{ message.content }}
              </div>
            </div>
            <div v-else class="other-message">
              <div class="message-header">
                <span class="sender">{{ getUserNameById(message.from) }}</span>
                <span class="time">{{ formatTime(message.timestamp) }}</span>
              </div>
              <div class="message-content">
                {{ message.content }}
              </div>
            </div>
          </div>
        </div>
        <!-- 底部输入区域 -->
        <div class="chat-footer">
          <el-input v-model="inputMessage" placeholder="请输入消息内容" @keyup.enter.native="sendMessage" style="flex: 1; margin: 0 10px;"></el-input>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </div>
      <!-- 未选择用户时显示提示信息 -->
      <div v-else class="no-selection">
        <span>请选择要聊天的居民</span>
      </div>
    </div>
  </div>
</template>

<script>
import WebSocketService from '../../service/websocket.service.js';
import axios from 'axios';

export default {
  name: 'ChatView',
  data() {
    return {
      username: '', // 当前用户的用户名（仅用于显示）
      userId: '', // 当前用户的ID（用于消息处理）
      messages: [], // 消息列表
      residents: [], // 居民列表
      inputMessage: '', // 输入框内容
      messageType: 'USER', // 消息类型，默认设为私聊
      privateChatTarget: '', // 私聊目标用户名（仅用于显示）
      selectedUserId: '', // 选中的用户ID（用于消息处理）
      wsService: null // WebSocket服务实例
    };
  },
  computed: {
    // 根据当前选中的聊天对象过滤消息
    filteredMessages() {
      if (!this.privateChatTarget || !this.selectedUserId) {
        return [];
      }
      
      // 将所有比较值转换为字符串，确保类型一致
      const currentUserId = String(this.userId);
      const targetUserId = String(this.selectedUserId);
      
      // 筛选出与当前选中用户相关的消息
      return this.messages.filter(msg => {
        // 系统消息始终显示
        if (msg.type === 'SYSTEM') {
          return true;
        }
        
        // 将消息中的from和to也转换为字符串进行比较
        const msgFrom = String(msg.from);
        const msgTo = String(msg.to);
        
        // 只显示与当前用户的私聊消息，且必须是用户角色或自己发送的消息
        return ((msgFrom === currentUserId && msgTo === targetUserId) || 
                (msgFrom === targetUserId && msgTo === currentUserId)) && 
               (msg.role === 'USER' || msgFrom === currentUserId);
      });
    }
  },
  mounted() {
    // 从sessionStorage获取用户信息
    this.username = sessionStorage.getItem('username') || '';
    this.userId = sessionStorage.getItem('userId') || '';
    
    // 初始化WebSocket连接
    this.initWebSocket();
    // 加载居民列表
    this.loadResidentsList();
  },
  beforeDestroy() {
    // 组件销毁前断开WebSocket连接
    if (this.wsService) {
      this.wsService.disconnect();
    }
  },
  methods: {
    // 初始化WebSocket连接
    initWebSocket() {
      this.wsService = new WebSocketService(this.userId);
      this.wsService.setOnMessageCallback((message) => {
        this.handleMessage(message);
      });
      this.wsService.setOnStatusCallback((status) => {
        this.handleStatusChange(status);
      });
      this.wsService.connect();
    },
    
    // 加载居民列表
    loadResidentsList() {
      axios.get('/api/resident/findResident')
        .then(res => {
          this.residents = res.data.data || [];
          // 过滤掉当前用户自己（使用userId）
          this.residents = this.residents.filter(user => String(user.residentId) !== String(this.userId));
        })
        .catch(error => {
          console.error('获取居民列表失败:', error);
          this.$message.error('获取居民列表失败');
        });
    },

    // 处理接收到的消息 - 只接收用户角色的消息或自己发送的消息
    handleMessage(message) {
      try {
        // 解析消息，如果是字符串则解析为JSON对象
        const msg = typeof message === 'string' ? JSON.parse(message) : message;
        console.log(JSON.stringify(msg))
        
        // 只接收用户角色的消息或自己发送的消息，确保医生只与用户通信
        if (msg.type === 'SYSTEM' || msg.role === 'USER' || msg.from === this.userId) {
          // 将消息添加到消息列表
          this.messages.push(msg);
          // 自动滚动到底部
          this.$nextTick(() => {
            const messageList = this.$el.querySelector('.message-list');
            if (messageList) {
              messageList.scrollTop = messageList.scrollHeight;
            }
          });
        }
      } catch (error) {
        console.error('解析消息失败:', error);
      }
    },

    // 处理WebSocket连接状态变化
    handleStatusChange(status) {
      console.log('WebSocket状态变化:', status);
      if (status === 'CLOSED') {
        this.$message.error('WebSocket连接已关闭');
        this.$router.push('/login');
      } else if (status === 'ERROR') {
        this.$message.error('WebSocket连接出错');
      }
    },

    // 发送消息
    sendMessage() {
      if (!this.inputMessage.trim()) {
        this.$message.warning('请输入消息内容');
        return;
      }

      const message = {
        type: this.messageType,
        from: this.userId,
        to: this.selectedUserId,
        content: this.inputMessage,
        timestamp: new Date().getTime(),
        role: 'DOCTOR' // 医生端设置角色为DOCTOR
      };
      this.messages.push(message);
      console.log(JSON.stringify(message))
      this.wsService.sendMessage(message);
      this.inputMessage = '';
      
      // 自动滚动到底部
      this.$nextTick(() => {
        const messageList = this.$el.querySelector('.message-list');
        if (messageList) {
          messageList.scrollTop = messageList.scrollHeight;
        }
      });
    },

    // 选择聊天用户
    sendToUser(username, userId) {
      if (String(userId) === String(this.userId)) {
        this.$message.warning('不能私聊自己');
        return;
      }

      // 设置聊天目标用户
      this.privateChatTarget = username // 保留用户名用于显示
      this.selectedUserId = userId; // 使用userId进行消息处理
      this.messageType = 'USER';
      
      // 清空输入框
      this.inputMessage = '';
      
      // 聚焦输入框
      this.$nextTick(() => {
        const input = this.$el.querySelector('.el-input__inner');
        if (input) {
          input.focus();
        }
      });
    },

    // 根据userId获取用户名（用于显示）
    getUserNameById(userId) {
      const user = this.residents.find(user => String(user.residentId) === String(userId));
      const userName = user ? user.residentName : '未知用户';
      // 查找消息中的该用户消息，获取角色信息
      const userMessage = this.messages.find(msg => msg.from === userId);
      if (userMessage && userMessage.role === 'USER') {
        return userName + ' (居民)';
      }
      return userName;
    },

    // 断开连接
    disconnect() {
      if (this.wsService) {
        this.wsService.disconnect();
      }
      sessionStorage.removeItem('username');
      sessionStorage.removeItem('userId');
      this.$router.push('/login');
    },

    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${hours}:${minutes}:${seconds}`;
    },

    // 生成唯一消息ID
    getUniqueMessageKey(message) {
      if (message.type === 'SYSTEM') {
        return `${message.type}_${message.timestamp}`;
      } else {
        const recipient = message.to || 'ALL';
        return `${message.from}_${recipient}_${message.type}_${message.timestamp}`;
      }
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.chat-header {
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.chat-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  padding: 20px;
  gap: 20px;
}

/* 居民列表样式 */
.user-list-container {
  width: 280px;
  background-color: #fff;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-list-container h3 {
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #e6e6e6;
  background-color: #fafafa;
  font-size: 16px;
  border-radius: 5px 5px 0 0;
}

.user-item-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  margin-bottom: 8px;
  background-color: #f5f7fa;
  border-radius: 8px;
  gap: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.user-item:hover {
  background-color: #e6f7ff;
  transform: translateX(5px);
}

.user-item span {
  flex: 1;
  font-size: 14px;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-size: 14px;
}

/* 聊天窗口样式 */
.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-window-header {
  padding: 15px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #e6e6e6;
  background-color: #fafafa;
}

.chat-window-header span {
  font-weight: 500;
  font-size: 16px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fafafa;
}

.message-item {
  margin-bottom: 20px;
}

.system-message {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin: 10px 0;
}

.self-message, .other-message {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.self-message {
  align-items: flex-end;
  margin-left: auto;
}

.other-message {
  align-items: flex-start;
  margin-right: auto;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
  font-size: 12px;
  color: #666;
}

.message-content {
  padding: 10px 15px;
  border-radius: 10px;
  background-color: #fff;
  border: 1px solid #e6e6e6;
  word-break: break-word;
  line-height: 1.5;
}

.self-message .message-content {
  background-color: #95ec69;
  border: none;
}

/* 未选择居民时的提示 */
.no-selection {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #999;
  font-size: 16px;
}

/* 底部输入区域 */
.chat-footer {
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  gap: 10px;
}

.chat-footer .el-input__inner {
  min-height: 40px;
  font-size: 14px;
  padding: 8px 15px;
}

.chat-footer .el-button {
  height: 40px;
  padding: 0 20px;
}
</style>